package 路径总和;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 路径总和 II
 * 递归加回溯
 * @date 2022/11/6 10:48
 */
public class Demo113 {
    //Definition for a binary tree node.
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        //最终结果
        List<List<Integer>>  res=new ArrayList<>();
        if(root==null){
            return res;
        }
        //递归结果集
        List<List<Integer>>  trackBackRes=new ArrayList<>();
        //单条路径
        List<Integer> singlePath=new ArrayList<>();
        trackBack(root,trackBackRes,singlePath);

        for (int i = 0; i < trackBackRes.size(); i++) {
            if (trackBackRes.get(i).stream().mapToInt(s->s).sum()==targetSum) {
                res.add(trackBackRes.get(i));
            }
        }
      return res;
    }

    private void trackBack(TreeNode root, List<List<Integer>> trackBackRes, List<Integer> singlePath) {
        singlePath.add(root.val);
        //到了叶子节点，添加到trackBackRes
        if(root.left==null&&root.right==null){
            ArrayList<Integer> arrayList = new ArrayList<>(singlePath);
            trackBackRes.add(arrayList);
            return;
        }
        //递归回溯
        if(root.left!=null){
            //递归
            trackBack(root.left,trackBackRes,singlePath);
            //回溯
            singlePath.remove(singlePath.size()-1);
        }
        if(root.right!=null){
            //递归
            trackBack(root.right,trackBackRes,singlePath);
            //回溯
            singlePath.remove(singlePath.size()-1);
        }
    }
}
